package com.my.interceptors;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.my.annotations.StatisticsVisitUsers;

public class VisitUsersInterceptor implements Interceptor
{

	@Override
	@SuppressWarnings("unchecked")
	public void intercept(Invocation inv) {
		// 1 将其他方法统计中以当前sessionId为key的统计记录抹除 (一个sessionId只统计一个当前访问的方法)
		ServletContext application = inv.getController().getSession().getServletContext();
		Enumeration<String> keys = application.getAttributeNames();
		while (keys.hasMoreElements()) {
			String k = keys.nextElement();
			if (k.equals(inv.getMethodName()))
				continue;
			Object o = application.getAttribute(k);
			if (o instanceof Map) {
				Map<String, Object> users = (Map<String, Object>) o;
				users.remove(inv.getController().getSession().getId());
				if (users.size() == 0) {
					application.removeAttribute(k);
					System.out.println("最后一个访问" + k + "方法的人也走了，Application 移除" + k);
				} else
					application.setAttribute(k, users);
				System.out.println("访问【" + k + "】方法的【" + inv.getController().getSession().getId() + "】被移除啦！");
			}
		}
		// 2 通过访问的方法名为key取出存放在Application作用域中针对该方法的访问人数的统计容器(Map)
		Map<String, Object> users = (Map<String, Object>) inv.getController().getRequest().getServletContext()
				.getAttribute(inv.getMethodName());
		if (null == users) {
			users = new HashMap<String, Object>();
		}

		StatisticsVisitUsers annotation = inv.getMethod().getAnnotation(StatisticsVisitUsers.class);
		if (null != annotation) {
			//有注解，users+1
			users.put(inv.getController().getSession().getId(), inv.getMethodName());
			inv.getController().getSession().getServletContext().setAttribute(inv.getMethodName(), users);
		}
		inv.invoke();
	}

}
